package net.zz.base.interceptor;

import net.zz.base.exception.CommonException;
import net.zz.base.plug.JsonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by ZaoSheng on 2015/5/9.
 */
@Component
public class ExceptionInterceptor implements HandlerExceptionResolver {

	private final static String error = "{\"ZZCode\":%s,\"message\":\"%s\"}";

	@Autowired
	private MessageSource msg;

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		Map<String,Object> data = new HashMap<String,Object>();
		System.out.println(handler);
		System.out.println("resolveException Thread id:"
				+ Thread.currentThread().getId());
		try {
			if (ex instanceof CommonException) {
				CommonException m = (CommonException) ex ;
				data.put("ZZCode", m.getCode());
				data.put("message", m.getMessage());
				//data.put("message",msg.getMessage("MZCode_"+m.getCode(), new Object[]{}, Locale.CHINA));
			}   else if (ex instanceof IllegalArgumentException) {
				data.put("ZZCode", 10000);
				data.put("message",ex.getMessage());
			} else {

                int MzCode = 500;
                String message = "Server error - [500]";
                if (ex.getCause() != null && ex.getCause() instanceof CommonException)
                {
                    CommonException m = (CommonException) ex.getCause();
                    MzCode = m.getCode();
                    message = m.getMessage();
                }else{
                    ex.printStackTrace();
                }
				data.put("ZZCode", MzCode);
				data.put("message", message);
			}
			String msgText = JsonMapper.entityToJson(data);
			OutputStream outputStream = response.getOutputStream();
			outputStreamWrite(outputStream,msgText);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

		}
//		return null;
		return new ModelAndView();
	}

	private boolean outputStreamWrite(OutputStream outputStream, String text) {
		try {
			outputStream.write(text.getBytes("UTF-8"));
			outputStream.flush();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
